package com.cobra.minio.service.impl;

import com.cobra.minio.config.MinIoTemplate;
import com.cobra.minio.dto.ChunkUploadUrlDTO;
import com.cobra.minio.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author tuine
 * @date 2021/3/23
 */
@Service
public class UploadServiceImpl implements UploadService {


    @Autowired
    MinIoTemplate minIoTemplate;

    @Override
    public Map<String, String> initMultiPartUploadUrl(String path, String filename, String uploadId, Integer totalChunks, String contentType) {
        path = path.replaceAll("/+", "/");
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        String filePath = path + "/" + filename;

        Map<String, String> map = new LinkedHashMap<>();
        // TODO::单文件上传可拆分，这里只做演示，可直接上传完成
        if (totalChunks == 1) {
            String uploadObjectUrl = minIoTemplate.getUploadObjectUrl(filePath);
            map.put(String.valueOf(1), uploadObjectUrl);
        } else {
            map = minIoTemplate.initMultiPartUpload(filePath, uploadId, totalChunks, contentType);
        }
        return map;
    }


    @Override
    public ChunkUploadUrlDTO initMultiPartUploadUrlV2(String path, String filename, String uploadId, Integer totalChunks, Integer partNumber, String contentType) {
        path = path.replaceAll("/+", "/");
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        String filePath = path + "/" + filename;
        ChunkUploadUrlDTO chunkUploadUrlDTO = ChunkUploadUrlDTO.builder().totalChunks(totalChunks).partNumber(partNumber).build();
        if (totalChunks == 1) {
            String uploadObjectUrl = minIoTemplate.getUploadObjectUrl(filePath);
            chunkUploadUrlDTO.setUrl(uploadObjectUrl);
        } else {
            String chunkUploadUrl = minIoTemplate.initMultiPartUploadByPartNumber(filePath, uploadId, partNumber, contentType);
            chunkUploadUrlDTO.setUrl(chunkUploadUrl);
        }
        return chunkUploadUrlDTO;
    }

    @Override
    public boolean mergeMultipartUpload(String objectName, String uploadId) {
        return minIoTemplate.mergeMultipartUpload(objectName, uploadId);
    }
}
